#!/usr/bin/ruby

##
## MoneYou Scraper
##
## This is a little tool to automatically query the account balance
## from MoneYou? accounts. This comes in handy as MoneYou? doesn't
## offer any API like HBCI/FinTS.
##
## Usage: ./moneyou.rb <account-id> <password>
##
##
## Licensed under the Apache License, Version 2.0 (the "License"); you may not
## use this file except in compliance with the License. You may obtain a copy of
## the License at
## 
## http://www.apache.org/licenses/LICENSE-2.0
## 
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
## WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
## License for the specific language governing permissions and limitations under
## the License.
## 

require "rexml/document"
include REXML

USER_ID = ARGV[0]
PASSWORD = ARGV[1]

SESSION_COOKIE_FILE = 'session-cookie.txt'
COOKIES_FILE = 'cookies.txt'

def make_cookie()
	session_cookie_file = File.new(SESSION_COOKIE_FILE, 'r')
	cookies = session_cookie_file.read
	session_cookie_file.close
	cookies += "secure.moneyou.de	FALSE	/exp	FALSE	0	nomabt		#{USER_ID}\n"
	cookies += "secure.moneyou.de	FALSE	/exp	FALSE	0	loginabt	#{USER_ID}"

	cookie_file = File.new('cookies.txt', 'w+')
	cookie_file.write(cookies)
	cookie_file.close
end

`wget -O - --save-cookies #{SESSION_COOKIE_FILE} --keep-session-cookies https://secure.moneyou.de/exp/jsp/authenticationDE.jsp 2>&1`
raise "wget not successful" if $?.exitstatus != 0
make_cookie()
`wget -O - --load-cookies #{COOKIES_FILE} --save-cookies cookies.txt --keep-session-cookies --header='Content-Type:application/x-www-form-urlencoded' --post-data 'first_pass_done=Y&id=#{USER_ID}&password=#{PASSWORD}&Subm01=Anmelden&mltsoc=1' https://secure.moneyou.de/exp/jsp/authenticationDE.jsp 2>&1`
raise "wget not successful" if $?.exitstatus != 0
response = `wget -O - --load-cookies #{COOKIES_FILE} --header='Content-Type:application/x-www-form-urlencoded' https://secure.moneyou.de/exp/jsp/entrypoint.jsp?state=000001 2>/dev/null`
raise "wget not successful" if $?.exitstatus != 0

xml = ""
found_start = false
found_end = false
response.each_line do |line|
	if line.start_with?("<?xml")
		found_start = true
	end
	if found_start && line.start_with?("-->")
		found_end = true
	end
	if found_start && !found_end
		xml += line + "\n"
	end
end

doc = Document.new(xml)
overview_elements = doc.elements.to_a("/xml/overview")
raise "Invalid overview_elements: #{overview_elements}" if overview_elements.length != 1

saldo = overview_elements[0].attributes['saldo']

euro_index = saldo.index("EUR")
raise "Invalid saldo: #{saldo}" if euro_index.nil?

saldo = saldo[0, euro_index]
saldo.strip!

saldo = saldo.sub('.', '').sub(',', '.')
saldo = saldo.to_f

print "#{saldo}\n"
